<?php
namespace Core\CoreComponents\UsersManager;
use Core;

require_once(COMPONENTS_DIR . 'UsersManager/IUsers.php');
require_once(CONTRACTS_DIR . 'user.entity.php');

/**
* This interface provide all accessible methods on Users module
*
* @method ServiceResponse authenticate($login, $password)
*/
class Users implements IUsers
{
	/**
	* Authenticate an user
	* 
	* @param string $login The user's login 
	* @param string $password The user's password 
	*
	* @return ServiceResponse This response contains the user object
	*/
	public function authenticate($login, $password)
	{
		Core\CoreCommons\Logger::Info("authenticate $login, $password");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
		
			$session->CreateCriteria('User');
			$session->AddCriteria(Core\Datastorage\Expression::SQL_EQ('Login', $login));
			$session->AddCriteria(Core\Datastorage\Expression::SQL_EQ('Password', $password));
			$user = $session->UniqueResult();
			
			if(isset($user) == false)
			{
				throw new \Exception(Core\CoreCommons\Localization::Get("Users_UserNotFound"));
			}
			
			if($user->State == Core\CoreContracts\StateUser::NotValid)
			{
				$user->State = Core\CoreContracts\StateUser::Online;
				$session->Update($user);
			}
				
			$response = new Core\CoreCommons\ServiceResponse($user);

			$session->Close();
			
			//Save the user on a session
			$_SESSION["_" . $user->Id] = $user;
			
			Core\CoreCommons\Logger::Info("authentification is finished");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/*
	* Check the user authorization
	*
	* @param int $userid The user unique identifier
	*
	* @return ServiceResponse This response contains the user object or null
	*/
	public function checkUserAuthorization($userid)
	{
		Core\CoreCommons\Logger::Info("checkUserAuthorization $userid");
		
		$response = null;
		
		try
		{	
			$result = null;
			if(isset($_SESSION["_" . $userid]))
			{
				$result = $_SESSION["_" . $userid];
			}
			else
			{
				$result = null;
			}
			
			$response = new Core\CoreCommons\ServiceResponse($result);
			
			Core\CoreCommons\Logger::Info("checkUserAuthorization $userid is finished");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/*
	* Set user as online
	*
	* @param int $userid The user unique identifier
	*
	* @return ServiceResponse This response contains the user 
	*/
	public function setUserAsOnline($userid)
	{
		Core\CoreCommons\Logger::Info("setUserAsOnline $userid");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$user = $session->Load('User', $userid);
			
			if(isset($user) == false)
			{
				throw new \Exception("L'utilisateur #$userid est introuvable");
			}
			
			$user->Online();
			
			$fieldsToUpdate = array('State' => $user->State, 'ModificationDate' => $user->ModificationDate);
			
			$result = $session->Update($user, $fieldsToUpdate);
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("User $userid was updated to online");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/*
	* Set user as offline
	*
	* @param int $userid The user unique identifier
	*
	* @return ServiceResponse This response contains the user 
	*/
	public function setUserAsOffline($userid)
	{
		Core\CoreCommons\Logger::Info("setUserAsOffline $userid");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$user = $session->Load('User', $userid);
			
			if(isset($user) == false)
			{
				throw new \Exception("L'utilisateur #$userid est introuvable");
			}
			
			$user->Offline();
			
			$fieldsToUpdate = array('State' => $user->State, 'ModificationDate' => $user->ModificationDate);
			
			$result = $session->Update($user, $fieldsToUpdate);
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("User $userid was updated to offline");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Get online users
	*
	* @return ServiceResponse This response contains all online users
	*/
	public function getOnlineUsers()
	{
		Core\CoreCommons\Logger::Info("getOnlineUsers");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
		
			$session->CreateCriteria('User');
			$session->AddCriteria(Core\Datastorage\Expression::SQL_EQ('State', Core\CoreContracts\StateUser::Online));
			$result = $session->ListResult();
			
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();

			Core\CoreCommons\Logger::Info("Get online users is finished");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Get all users
	*
	* @return ServiceResponse This response contains all users
	*/
	public function getUsers()
	{
		Core\CoreCommons\Logger::Info("getUsers");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
		
			$session->CreateCriteria('User');
			$result = $session->ListResult();
			
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();

			Core\CoreCommons\Logger::Info("Get all users is finished");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Get all administrators
	*
	* @return ServiceResponse This response contains all administrators
	*/
	public function getAdministrators()
	{
		Core\CoreCommons\Logger::Info("getAdministrators");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
		
			$session->CreateCriteria('User');
			$session->AddCriteria(Core\Datastorage\Expression::SQL_EQ('Profile', Core\CoreContracts\ProfileUser::Administrator));
			$result = $session->ListResult();
			
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();

			Core\CoreCommons\Logger::Info("Get all administrators is finished");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Get all user more or upper members
	*
	* @return ServiceResponse This response contains users
	*/
	public function getUsersMemberMinimum()
	{
		Core\CoreCommons\Logger::Info("getUsersMemberMinimum");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
		
			$session->CreateCriteria('User');
			$session->AddCriteria(Core\Datastorage\Expression::SQL_SUPOREQ('Profile', Core\CoreContracts\ProfileUser::Volunteer));
			$result = $session->ListResult();
			
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();

			Core\CoreCommons\Logger::Info("Get all users mor than members or equals is finished");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/*
	* Add an user
	*
	* @param string $firstname The user's firstname 
	* @param string $lastname The user's lastname 
	* @param string $company The user's company 
	* @param string $email The user's email 
	* @param string $phonenumber The user's phonenumber 
	* @param string $webaddress The user's webaddress 
	* @param int $profile The user's profile 
	*
	* @return ServiceResponse This response contains the added user
	*/
	public function addUser($firstname, $lastname, $company, $email, $phonenumber, $webaddress, $profile)
	{
		Core\CoreCommons\Logger::Info("addUser $firstname, $lastname, $company, $email, $phonenumber, $webaddress, $profile");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			//control email duplication
			$session->CreateCriteria('User');
			$session->AddCriteria(Core\Datastorage\Expression::SQL_EQ('Email', $email));
			$existingUser = $session->UniqueResult();
			
			if($existingUser != null)
			{
				throw new \Exception("Un utilisateur possède déjà ce mail.");
			}
			
			$login = sprintf("%s%s", substr(strtolower($firstname), 0, count($firstname)), strtolower($lastname));
			$password = $this->generateRandomString();
			$hashPassword = sha1($password);
			$user = Core\CoreContracts\User::Create($firstname, $lastname, $company, $email, $phonenumber, $webaddress, $login, $hashPassword, $profile);

			// Save the user on database
			$result = $session->Save($user);
			$response = new Core\CoreCommons\ServiceResponse($result);
			
			if($response->isFailed)
			{
				throw new \Exception($response->exception);
			}

			$session->Close();
			Core\CoreCommons\Logger::Info(sprintf("User %s added", $user));
			
			Core\CoreCommons\Logger::Info(sprintf("Send a mail to the new user %s in order to inform him", $user));
			$values = array();
			$values['#firstname'] = $firstname;
			$values['#lastname'] = $lastname;
			$values['#login'] = $login;
			$values['#$password'] = $password;
			$mail = new Core\CoreCommons\Mail("NewUser", $values); 
			$mail->Send($email);
			
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/*
	* Add a new user
	*
	* @param string $firstname The user's firstname 
	* @param string $lastname The user's lastname 
	* @param string $email The user's email 
	*
	* @return ServiceResponse This response contains the added user
	*/
	public function addNewUser($firstname, $lastname, $email)
	{
		Core\CoreCommons\Logger::Info("addNewUser $firstname, $lastname, $email");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			//control email duplication
			$session->CreateCriteria('User');
			$session->AddCriteria(Core\Datastorage\Expression::SQL_EQ('Email', $email));
			$existingUser = $session->UniqueResult();
			
			if($existingUser != null)
			{
				throw new \Exception("Un utilisateur possède déjà ce mail.");
			}
			
			$login = sprintf("%s%s", substr(strtolower($firstname), 0, count($firstname)), strtolower($lastname));
			$password = $this->generateRandomString();
			$hashPassword = sha1($password);
			$user = Core\CoreContracts\User::Create($firstname, $lastname, "", $email, "", "", $login, $hashPassword, Core\CoreContracts\ProfileUser::User);

			// Save the user on database
			$result = $session->Save($user);
			$response = new Core\CoreCommons\ServiceResponse($result);
			
			if($response->isFailed)
			{
				throw new \Exception($response->exception);
			}

			$session->Close();
			Core\CoreCommons\Logger::Info(sprintf("User %s added", $user));
			
			Core\CoreCommons\Logger::Info(sprintf("Send a mail to the new user %s in order to inform him", $user));
			$values = array();
			$values['#firstname'] = $firstname;
			$values['#lastname'] = $lastname;
			$values['#login'] = $login;
			$values['#password'] = $password;
			$values['#hashPassword'] = $hashPassword;
			$mail = new Core\CoreCommons\Mail("NewUser", $values); 
			$mail->Send($email);
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/*
	* Add a new member
	*
	* @param string $firstname The user's firstname 
	* @param string $lastname The user's lastname 
	* @param string $email The user's email 
	* @param string $object The user's object 
	* @param string $message The user's message 
	*
	* @return ServiceResponse This response contains the added user
	*/
	public function demandNewMember($firstname, $lastname, $email, $object, $message)
	{
		Core\CoreCommons\Logger::Info("demandNewMember $firstname, $lastname, $email, $object, $message");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$login = sprintf("%s%s", substr(strtolower($firstname), 0, count($firstname)), strtolower($lastname));
			$password = $this->generateRandomString();
			$hashPassword = sha1($password);
			$user = Core\CoreContracts\User::Create($firstname, $lastname, "", $email, "", "", $login, $hashPassword, 2);

			// Save the user on database
			$result = $session->Save($user);
			$response = new Core\CoreCommons\ServiceResponse($result);
			
			if($response->isFailed)
			{
				throw new \Exception($response->exception);
			}

			$session->Close();
			Core\CoreCommons\Logger::Info(sprintf("User %s added", $user));
			
			Core\CoreCommons\Logger::Info(sprintf("Send a mail to the new user %s in order to inform him", $user));
			$values = array();
			$values['#firstname'] = $firstname;
			$values['#lastname'] = $lastname;
			$mail = new Core\CoreCommons\Mail("NewMember", $values); 
			$mail->Send($email);
			
			$values = array();
			$values['#firstname'] = $firstname;
			$values['#lastname'] = $lastname;
			$values['#object'] = $object;
			$values['#message'] = $message;
			$mail = new Core\CoreCommons\Mail("DemandNewMember", $values); 
			
			//To administrators
			$to = array();
			$administrators = $this->getAdministrators();
			
			foreach($administrators->response as &$administrator)
			{
				array_push($to, $administrator->Email);
			}

			$mail->Send($to);
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/*
	* Send a contact mail
	*
	* @param string $firstname The user's firstname 
	* @param string $lastname The user's lastname 
	* @param string $email The user's email 
	* @param string $object The user's object 
	* @param string $message The user's message 
	*
	* @return ServiceResponse This response contains the added user
	*/
	public function sendContact($firstname, $lastname, $email, $object, $message)
	{
		Core\CoreCommons\Logger::Info("sendContact $firstname, $lastname, $email, $object, $message");
		
		$response = null;
		
		try
		{	
			$values = array();
			$values['#firstname'] = $firstname;
			$values['#lastname'] = $lastname;
			$values['#email'] = $email;
			$values['#object'] = $object;
			$values['#message'] = $message;
			$mail = new Core\CoreCommons\Mail("ContactForm", $values); 
			
			//To administrators
			$to = array();
			$administrators = $this->getAdministrators();
			
			foreach($administrators->response as &$administrator)
			{
				array_push($to, $administrator->Email);
			}

			$sent = $mail->Send($to);
			
			if($sent == false)
			{
				throw new \Exception("Probleme lors de l'envoi du mail...");
			}
			
			$response = new Core\CoreCommons\ServiceResponse($sent);
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/*
	* valid an user
	*
	* @param string $password The user's password 
	*
	* @return ServiceResponse This response contains the validate user
	*/
	public function validUserEmail($password)
	{
		Core\CoreCommons\Logger::Info("validUserEmail");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
		
			$session->CreateCriteria('User');
			$session->AddCriteria(Core\Datastorage\Expression::SQL_EQ('Password', $password));
			$user = $session->UniqueResult();
			
			if(isset($user))
			{
				$user->State = Core\CoreContracts\StateUser::Online;
			}
			else
			{
				throw new \Exception("Utilisateur introuvable."); 
			}
			
			$user->ModificationDate = date("Y-m-d H:i:s");
			
			$fieldsToUpdate = array('State' => $user->State, 'ModificationDate' => $user->ModificationDate);

			$session->Update($user, $fieldsToUpdate);
			
			$response = new Core\CoreCommons\ServiceResponse($user);

			$session->Close();
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Get all profiles
	*
	* @return ServiceResponse This response contains all profiles
	*/
	public function getProfiles()
	{
		Core\CoreCommons\Logger::Info("getProfiles");
		
		$response = null;
		
		try
		{	
			$profileUsers = new Core\CoreContracts\ProfileUser();
			
			$response = new Core\CoreCommons\ServiceResponse($profileUsers->getArray());

			Core\CoreCommons\Logger::Info("Get all profiles is finished");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/*
	* Delete an user
	*
	* @param int $id The user's identifier 
	*
	* @return ServiceResponse This response contains the deleted user
	*/
	public function deleteUser($id)
	{
		Core\CoreCommons\Logger::Info("deleteUser $id");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$user = $session->Load('User', $id);
			
			if(isset($user) == false)
			{
				throw new \Exception("L'utilisateur #$id est introuvable");
			}

			$result = $session->Delete($user);
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("User $id deleted");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	* Attach a avatar on an user
	*
	* @param int $idUser The user id
	* @param binary[] $file The avatar file
	* @param string $mime The avatar file mime type
	* @param string $extension The avatar file extension
	* 
	* @return ServiceResponse This response contains the user with his avatar
	*/
	public function attachAvatarOnAnUser($idUser, $content, $mime, $extension)
	{	
		Core\CoreCommons\Logger::Info("attachAvatarOnAnUser $idUser, $mime, $extension");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$user = $session->Load('User', $idUser);
			
			if(isset($user) == false)
			{
				throw new \Exception("L'utilisateur #$idUser est introuvable");
			}
			
			$content = mysql_real_escape_string($content);
			
			$user->Avatar = $content;
			$user->AvatarMime = $mime;
			$user->AvatarExtension = $extension;
			$user->ModificationDate = date("Y-m-d H:i:s");
			
			$fieldsToUpdate = array('Avatar' => $user->Avatar, 'AvatarMime' => $user->AvatarMime, 'AvatarExtension' => $user->AvatarExtension,  'ModificationDate' => $user->ModificationDate);
			
			$result = $session->Update($user, $fieldsToUpdate);
			
			$user = $session->Load('User', $idUser);
			
			$response = new Core\CoreCommons\ServiceResponse($user);

			$session->Close();
			Core\CoreCommons\Logger::Info("User $idUser has a new avatar");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/*
	* Update an user
	*
	* @param int $id The unique identifier of a user
	* @param string $firstname The user's firstname 
	* @param string $lastname The user's lastname 
	* @param string $email The user's email 
	* @param string $phonenumber The user's phonenumber 
	* @param string $login The user's login 
	* @param string $password The user's password 
	* @param int $profile The user's profile 
	*
	* @return ServiceResponse This response contains the updated user
	*/
	public function updateUser($id, $firstname, $lastname, $company, $email, $phonenumber, $webaddress, $login, $profile)
	{
		Core\CoreCommons\Logger::Info("updateUser id : $id, firstname : $firstname, lastname : $lastname, company : $company, email : $email, phonenumber : $phonenumber, webaddress : $webaddress, login : $login, profile : $profile");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			//control email duplication
			$session->CreateCriteria('User');
			$session->AddCriteria(Core\Datastorage\Expression::SQL_EQ('Email', $email));
			$existingUser = $session->UniqueResult();
			
			if($existingUser != null && $existingUser->Id != $id)
			{
				throw new \Exception("Un utilisateur possède déjà ce mail.");
			}
			
			$user = $session->Load('User', $id);
			
			if(isset($user) == false)
			{
				throw new \Exception("L'utilisateur #$id est introuvable.");
			}
			
			$user->Firstname = $firstname;
			$user->Lastname = $lastname;
			$user->Company = $company;
			$user->Email = $email;
			$user->PhoneNumber = $phonenumber;
			$user->WebAddress = $webaddress;
			$user->Login = $login;
			$user->Profile = $profile;
			$user->ModificationDate = date("Y-m-d H:i:s");
			
			$fieldsToUpdate = array('Firstname' => $user->Firstname, 'Lastname' => $user->Lastname, 'Company' => $user->Company, 'Email' => $user->Email, 'PhoneNumber' => $user->PhoneNumber, 'WebAddress' => $user->WebAddress, 'Login' => $user->Login, 'Profile' => $user->Profile, 'ModificationDate' => $user->ModificationDate);

			$result = $session->Update($user, $fieldsToUpdate);
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("User $id was updated");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/*
	* Update users's informations
	*
	* @param int $id The unique identifier of a user
	* @param string $firstname The user's firstname 
	* @param string $lastname The user's lastname 
	* @param string $email The user's email 
	* @param string $phonenumber The user's phonenumber 
	* @param string $login The user's login 
	*
	* @return ServiceResponse This response contains the updated user
	*/
	public function updateUserInformations($id, $firstname, $lastname, $company, $email, $phonenumber, $webaddress, $login)
	{
		Core\CoreCommons\Logger::Info("updateUserInformations id : $id, firstname : $firstname, lastname : $lastname, company : $company, email : $email, phonenumber : $phonenumber, webaddress : $webaddress, login : $login");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			//control email duplication
			$session->CreateCriteria('User');
			$session->AddCriteria(Core\Datastorage\Expression::SQL_EQ('Email', $email));
			$existingUser = $session->UniqueResult();
			
			if($existingUser != null && $existingUser->Id != $id)
			{
				throw new \Exception("Un utilisateur possède déjà ce mail.");
			}
			
			$user = $session->Load('User', $id);
			
			if(isset($user) == false)
			{
				throw new \Exception("L'utilisateur #$id est introuvable");
			}
			
			$user->Firstname = $firstname;
			$user->Lastname = $lastname;
			$user->Company = $company;
			$user->Email = $email;
			$user->PhoneNumber = $phonenumber;
			$user->WebAddress = $webaddress;
			$user->Login = $login;
			$user->ModificationDate = date("Y-m-d H:i:s");
			
			$fieldsToUpdate = array('Firstname' => $user->Firstname, 'Lastname' => $user->Lastname, 'Company' => $user->Company, 'Email' => $user->Email, 'PhoneNumber' => $user->PhoneNumber, 'WebAddress' => $user->WebAddress, 'Login' => $user->Login, 'ModificationDate' => $user->ModificationDate);
			
			$result = $session->Update($user, $fieldsToUpdate);
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("User $id was updated");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/*
	* Get an user
	*
	* @param int $id The user's identifier 
	*
	* @return ServiceResponse This response contains the user
	*/
	public function getUser($id)
	{
		Core\CoreCommons\Logger::Info("getUser $id");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$user = $session->Load('User', $id);
			
			if(isset($user) == false)
			{
				throw new \Exception("L'utilisateur #$id est introuvable");
			}

			$response = new Core\CoreCommons\ServiceResponse($user);

			$session->Close();
			Core\CoreCommons\Logger::Info("User $id loaded");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/*
	* Update users's informations
	*
	* @param int $id The unique identifier of a user
	* @param string $newPassword The user's new password 
	*
	* @return ServiceResponse This response contains the updated user
	*/
	public function updateUserPassword($id, $newPassword)
	{
		Core\CoreCommons\Logger::Info("updateUserPassword $id, $newPassword");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$user = $session->Load('User', $id);
			
			if(isset($user) == false)
			{
				throw new \Exception("L'utilisateur #$id est introuvable");
			}
			
			$hashPassword = sha1($newPassword);
			$user->Password = $hashPassword;
			$user->ModificationDate = date("Y-m-d H:i:s");
			
			$fieldsToUpdate = array('Password' => $user->Password, 'ModificationDate' => $user->ModificationDate);
			
			$result = $session->Update($user, $fieldsToUpdate);
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("User $id was updated");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/*
	* Reset user password
	*
	* @param int $userid The user unique identifier
	*
	* @return ServiceResponse This response contains the user object or null
	*/
	public function resetUserPassword($userid)
	{
		Core\CoreCommons\Logger::Info("resetUserPassword $userid");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$user = $session->Load('User', $userid);
			
			if(isset($user) == false)
			{
				throw new \Exception("L'utilisateur #$userid est introuvable");
			}
			
			$password = $this->generateRandomString();
			$hashPassword = sha1($password);
			$user->Password = $hashPassword;
			$user->ModificationDate = date("Y-m-d H:i:s");
			
			$fieldsToUpdate = array('Password' => $user->Password, 'ModificationDate' => $user->ModificationDate);
			
			$result = $session->Update($user, $fieldsToUpdate);
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("User $userid password was updated");
			
			Core\CoreCommons\Logger::Info(sprintf("Send a mail to user %s in order to inform him about resetting password", $user));
			$values = array();
			$values['#firstname'] = $firstname;
			$values['#lastname'] = $lastname;
			$values['#login'] = $login;
			$values['#$password'] = $password;
			$mail = new Core\CoreCommons\Mail("resetUserPassword", $values); 
			$mail->Send($email);
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/*
	* Generate a random string 
	* 
	* @todo Refactor this method on a helper class
	*/
	private function generateRandomString($length = 10) 
	{
		$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$randomString = '';
		for ($i = 0; $i < $length; $i++) 
		{
			$randomString .= $characters[rand(0, strlen($characters) - 1)];
		}
		return $randomString;
	}
}

?> 